package com.tangyuan.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.result.ResultCodeEnum;
import com.tangyuan.common.util.CommStatus;
import com.tangyuan.model.Music;
import com.tangyuan.model.User;
import com.tangyuan.video.mapper.MusicMapper;
import com.tangyuan.video.service.IMusicService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.List;

@Service
public class MusicServiceImpl extends ServiceImpl<MusicMapper, Music> implements IMusicService {
    @Autowired
    private MusicMapper musicMapper;

    @Override
    public Result saveApplyFrequency(BigInteger musicId, String token) {
        User user = CommStatus.getUser(token);
        if (user == null) {
            return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }
        if (musicId == null) {
            return Result.build(null, ResultCodeEnum.ARGUMENT_VALID_ERROR);
        }
        Music music = musicMapper.selectById(musicId);
        if (music == null) {
            return Result.build(null, ResultCodeEnum.NO_DATA);
        }
        music.setClickNum(music.getClickNum() + 1);
        if (musicMapper.updateById(music) > 0) {
            return Result.ok();
        }
        return Result.build(null, ResultCodeEnum.FAIL);
    }

    @Override
    public Result searchMusic(Integer pageNum, Integer pageSize, String musicName, Long userId) {
        if (userId == null) {
            return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }
        if (StringUtils.isBlank(musicName)) {
            return Result.build("请正确输入需要查询的内容", ResultCodeEnum.ARGUMENT_VALID_ERROR);
        }
        PageHelper.startPage(pageNum, pageSize);
        LambdaQueryWrapper<Music> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Music::getTitle, musicName);
        List<Music> musicList = musicMapper.selectList(lambdaQueryWrapper);
        return Result.ok(new PageInfo<>(musicList));
    }
}
